﻿using Microsoft.International.Converters.PinYinConverter;
using System.Text.RegularExpressions;

namespace Sgr
{
    public class PinYinConverterHelper
    {
        /// <summary>
        /// 将中文文本转换为拼音
        /// </summary>
        /// <param name="text">中文文本</param>
        /// <param name="islower">是否小写</param>
        /// <returns>拼音字符串</returns>
        public static string ToPinyin(string text, bool islower = true)
        {
            string result = string.Empty;
            text = Regex.Replace(text, @"[^\u4e00-\u9fa5]", string.Empty).Trim();
            foreach (char item in text)
            {
                var cc = new ChineseChar(item);
                if (cc.Pinyins.Count > 0 && cc.Pinyins[0].Length > 0)
                {
                    string temp = cc.Pinyins[0].ToString();
                    if (islower)
                    {
                        temp = temp.ToLower();
                    }
                    result += temp.Substring(0, temp.Length - 1);
                }
            }
            return result;
        }

        /// <summary>
        /// 将中文文本转换为首字母拼音缩写
        /// </summary>
        /// <param name="text">中文文本</param>
        /// <param name="islower">是否小写</param>
        /// <returns>拼音首字母缩写</returns>
        public static string ToFirstPinyin(string text, bool islower = true)
        {
            string result = string.Empty;
            text = Regex.Replace(text, @"[^\u4e00-\u9fa5]", string.Empty).Trim();
            foreach (var item in text)
            {
                var cc = new ChineseChar(item);
                if (cc.Pinyins.Count > 0 && cc.Pinyins[0].Length > 0)
                {
                    string temp = cc.Pinyins[0].ToString();
                    if (islower)
                    {
                        temp = temp.ToLower();
                    }
                    result += temp.Substring(0, 1);
                }
            }
            return result;
        }
    }
}